package com.nulldev.util.threading.event;

import java.util.Vector;

public class EventDispatcher implements Runnable {
	private boolean runs;
	
	private EventQueue eventQueue;
	
	private Vector<EventListener> listeners = new Vector<EventListener>();
	
	public EventDispatcher (EventQueue eventQueue) {
		this.eventQueue = eventQueue;
	}
	
	public void addListener(EventListener listener) {
		listeners.add(listener);
		//System.out.println("added: " + listener);
	}
	
	public void removeListener(EventListener listener) {
		listeners.remove(listener);
		//System.out.println("removed: " + listener);
	}
	
	public int countListeners() {
		return listeners.size();
	}
	
	public void start() {
		runs = true;
		new Thread(this).start();
	}
	
	public void run() {
		while (runs) {
			Event event = eventQueue.poll();
			
			for (int i=0; i<listeners.size(); i++) {
				//System.out.println("E: " + i);
				try {
					listeners.get(i).handleEvent(event);
				} catch (Exception e) {
					e.printStackTrace();
					listeners.remove(i);
					System.out.println("Exception wile processing event. Affected listener removed.");
				}
			}
		}
	}
	
	public boolean runs() {
		return runs;
	}
	
	public void stop() {
		runs = true;
	}
}
